const mysql = require('mysql2');

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT || 3306,
    database: 'SmartHomeDB'
});

function executeQuery(sql, params, callback) {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                console.error(`An error occurred while getting a connection from the pool: ${err}`);
                reject(err);
                return;
            }
            connection.query(sql, params, (err, results) => {
                connection.release();
                if (err) {
                    console.error(`An error occurred while executing SQL statement: ${err}`);
                    reject(err);
                    return;
                }
                if (callback) {
                    callback(null, results);
                }
                resolve(results);
            });
        });
    });
}

module.exports = {
    query: executeQuery
};